/**
 * @file CheckoutPage.jsx
 * @description 结算页面组件。
 */
import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Link, useNavigate } from 'react-router-dom';
import { clearCart } from '../store/cartSlice';
import toast from 'react-hot-toast';

const CheckoutPage = () => {
  const cartItems = useSelector((state) => state.cart.items);
  const currentUser = useSelector((state) => state.auth.user);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [validated, setValidated] = useState(false); // validated 状态仍然用于触发表单的（视觉）验证样式

  // ★★★ 硬编码的表单数据示例 ★★★
  const hardcodedBillingAddress = {
    firstName: '张 (Zhang)',
    lastName: '三 (San)',
    email: 'zhangsan@example.com',
    address: '北京市东城区长安街1号',
    address2: 'A座 101室',
    country: '中国',
    state: '北京',
    zip: '100010',
  };

  const hardcodedPaymentDetails = {
    paymentMethod: 'credit',
    ccName: 'ZHANG SAN',
    ccNumber: '1234567890123456',
    ccExpiration: '12/27',
    ccCvv: '123',
  };

  // 下面的 useState Hook 我们暂时不再通过 onChange 更新它们的值
  // 但保留它们是为了让 input 的 value 属性有值可绑定，使得表单看起来被“填充”了
  const [billingAddress, setBillingAddress] = useState(hardcodedBillingAddress);
  const [paymentDetails, setPaymentDetails] = useState(hardcodedPaymentDetails);


  // handleInputChange 函数暂时不再需要，因为我们不处理输入变化
  // const handleGenericInputChange = (e, setStateFunction) => { ... };
  // const handlePaymentMethodChange = (e) => { ... };


  let subtotal = 0;
  let totalItems = 0;
  cartItems.forEach(item => {
    subtotal += item.price * item.qty;
    totalItems += item.qty;
  });
  const shipping = totalItems > 0 ? 30.00 : 0;
  const totalAmount = subtotal + shipping;

  const handleFormSubmit = (event) => {
    event.preventDefault(); // 阻止表单默认提交
    const form = event.currentTarget;

    // 虽然我们硬编码了数据，但仍然可以进行一次简单的“提交时”验证视觉效果
    // 如果表单中的 required 字段因为硬编码的值是空的，这里会阻止
    if (form.checkValidity() === false) {
      event.stopPropagation();
      toast.error('表单数据不完整（尽管已硬编码）。');
      setValidated(true);
      return;
    }
    setValidated(true); // 触发视觉验证

    if (!currentUser || !currentUser.id) {
      toast.error('用户未登录，无法创建订单！');
      navigate('/login');
      return;
    }

    toast.loading('正在处理您的订单...', { duration: 1500 });

    setTimeout(() => {
      // ★★★ 使用硬编码的数据创建订单对象 ★★★
      const newOrder = {
        orderId: `ORD-${Date.now()}-${Math.floor(Math.random() * 1000)}`,
        userId: currentUser.id,
        date: new Date().toISOString(),
        items: [...cartItems],
        subtotal: parseFloat(subtotal.toFixed(2)),
        shipping: parseFloat(shipping.toFixed(2)),
        totalAmount: parseFloat(totalAmount.toFixed(2)),
        shippingAddress: { // 直接使用硬编码的地址
          fullName: `${hardcodedBillingAddress.firstName} ${hardcodedBillingAddress.lastName}`,
          email: hardcodedBillingAddress.email,
          address: hardcodedBillingAddress.address,
          address2: hardcodedBillingAddress.address2,
          country: hardcodedBillingAddress.country,
          state: hardcodedBillingAddress.state,
          zip: hardcodedBillingAddress.zip,
        },
        paymentMethod: hardcodedPaymentDetails.paymentMethod, // 使用硬编码的支付方式
        status: '处理中',
      };

      const allOrders = JSON.parse(localStorage.getItem('userOrders')) || [];
      allOrders.push(newOrder);
      localStorage.setItem('userOrders', JSON.stringify(allOrders));

      dispatch(clearCart());
      toast.success('订单提交成功！感谢您的购买。');
      navigate('/profile');
    }, 1500);
  };

  const EmptyCart = () => (
    <div className="container py-5">
      <div className="row">
        <div className="col-md-12 py-5 bg-light text-center">
          <h4 className="p-3 display-5">购物车中没有商品</h4>
          <Link to="/products" className="btn btn-outline-dark mx-4">
            继续购物
          </Link>
        </div>
      </div>
    </div>
  );

  const ShowCheckout = () => (
    <div className="container py-5">
      <div className="row my-4">
        <div className="col-md-5 col-lg-4 order-md-last">
          <div className="card mb-4">
            <div className="card-header py-3 bg-light">
              <h5 className="mb-0">订单摘要</h5>
            </div>
            <div className="card-body">
              <ul className="list-group list-group-flush">
                <li className="list-group-item d-flex justify-content-between align-items-center border-0 px-0 pb-0">
                  商品 ({totalItems})<span>${subtotal.toFixed(2)}</span>
                </li>
                <li className="list-group-item d-flex justify-content-between align-items-center px-0">
                  运费<span>${shipping.toFixed(2)}</span>
                </li>
                <li className="list-group-item d-flex justify-content-between align-items-center border-0 px-0 mb-3">
                  <div>
                    <strong>总金额</strong>
                  </div>
                  <span>
                    <strong>${totalAmount.toFixed(2)}</strong>
                  </span>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <div className="col-md-7 col-lg-8">
          <div className="card mb-4">
            <div className="card-header py-3">
              <h4 className="mb-0">账单地址 (已预填)</h4>
            </div>
            <div className="card-body">
              {/* 表单的 onChange 事件处理器已移除，value 指向 state，state 初始化为硬编码数据 */}
              <form className={`needs-validation ${validated ? 'was-validated' : ''}`} noValidate onSubmit={handleFormSubmit}>
                <div className="row g-3">
                  <div className="col-sm-6">
                    <label htmlFor="firstName" className="form-label">姓氏</label>
                    <input type="text" className="form-control" id="firstName" name="firstName" required 
                           value={billingAddress.firstName} readOnly /> {/* 添加 readOnly */}
                    <div className="invalid-feedback">
                      请输入有效的姓氏。
                    </div>
                  </div>

                  <div className="col-sm-6">
                    <label htmlFor="lastName" className="form-label">名字</label>
                    <input type="text" className="form-control" id="lastName" name="lastName" required 
                           value={billingAddress.lastName} readOnly /> {/* 添加 readOnly */}
                    <div className="invalid-feedback">
                      请输入有效的名字。
                    </div>
                  </div>

                  <div className="col-12">
                    <label htmlFor="email" className="form-label">邮箱 <span className="text-muted">(可选)</span></label>
                    <input type="email" className="form-control" id="email" name="email" placeholder="you@example.com" 
                           value={billingAddress.email} readOnly /> {/* 添加 readOnly */}
                    <div className="invalid-feedback">
                      请输入一个有效的邮箱地址。
                    </div>
                  </div>

                  <div className="col-12">
                    <label htmlFor="address" className="form-label">地址</label>
                    <input type="text" className="form-control" id="address" name="address" placeholder="例如：幸福路123号" required 
                           value={billingAddress.address} readOnly /> {/* 添加 readOnly */}
                    <div className="invalid-feedback">
                      请输入您的收货地址。
                    </div>
                  </div>

                  <div className="col-12">
                    <label htmlFor="address2" className="form-label">详细地址 <span className="text-muted">(可选)</span></label>
                    <input type="text" className="form-control" id="address2" name="address2" placeholder="例如：公寓、单元或楼层" 
                           value={billingAddress.address2} readOnly /> {/* 添加 readOnly */}
                  </div>

                  <div className="col-md-5">
                    <label htmlFor="country" className="form-label">国家/地区</label>
                    <select className="form-select" id="country" name="country" required 
                            value={billingAddress.country} disabled> {/* 使用 disabled */}
                      <option value="中国">中国</option>
                      <option value="美国">美国</option>
                      <option value="日本">日本</option>
                    </select>
                    <div className="invalid-feedback">
                      请选择一个有效的国家/地区。
                    </div>
                  </div>

                  <div className="col-md-4">
                    <label htmlFor="state" className="form-label">省/直辖市</label>
                    <select className="form-select" id="state" name="state" required
                            value={billingAddress.state} disabled> {/* 使用 disabled */}
                      <option value="北京">北京</option>
                      <option value="上海">上海</option>
                      <option value="广东">广东</option>
                      <option value="江苏">江苏</option>
                      <option value="浙江">浙江</option>
                    </select>
                    <div className="invalid-feedback">
                      请输入有效的省/直辖市。
                    </div>
                  </div>

                  <div className="col-md-3">
                    <label htmlFor="zip" className="form-label">邮政编码</label>
                    <input type="text" className="form-control" id="zip" name="zip" required pattern="[0-9]{6}" 
                           value={billingAddress.zip} readOnly /> {/* 添加 readOnly */}
                    <div className="invalid-feedback">
                      请输入有效的6位邮政编码。
                    </div>
                  </div>
                </div>

                <hr className="my-4" />

                <div className="form-check">
                  <input type="checkbox" className="form-check-input" id="same-address" name="sameAddress" defaultChecked disabled/>
                  <label className="form-check-label" htmlFor="same-address">送货地址与我的账单地址相同</label>
                </div>

                <div className="form-check">
                  <input type="checkbox" className="form-check-input" id="save-info" name="saveInfo" defaultChecked disabled/>
                  <label className="form-check-label" htmlFor="save-info">保存此信息以便下次使用</label>
                </div>

                <hr className="my-4" />

                <h4 className="mb-3">支付方式 (已预选)</h4>

                <div className="my-3">
                  <div className="form-check">
                    <input id="credit" name="paymentMethod" type="radio" className="form-check-input" required 
                           value="credit" checked={paymentDetails.paymentMethod === 'credit'} disabled />
                    <label className="form-check-label" htmlFor="credit">信用卡</label>
                  </div>
                  <div className="form-check">
                    <input id="debit" name="paymentMethod" type="radio" className="form-check-input" required 
                           value="debit" checked={paymentDetails.paymentMethod === 'debit'} disabled />
                    <label className="form-check-label" htmlFor="debit">借记卡</label>
                  </div>
                  <div className="form-check">
                    <input id="paypal" name="paymentMethod" type="radio" className="form-check-input" required 
                           value="paypal" checked={paymentDetails.paymentMethod === 'paypal'} disabled />
                    <label className="form-check-label" htmlFor="paypal">PayPal</label>
                  </div>
                </div>

                <div className="row gy-3">
                  <div className="col-md-6">
                    <label htmlFor="cc-name" className="form-label">持卡人姓名</label>
                    <input type="text" className="form-control" id="cc-name" name="ccName" required 
                           value={paymentDetails.ccName} readOnly /> {/* 添加 readOnly */}
                    <small className="text-muted">卡上显示的全名</small>
                    <div className="invalid-feedback">
                      请输入持卡人姓名。
                    </div>
                  </div>

                  <div className="col-md-6">
                    <label htmlFor="cc-number" className="form-label">卡号</label>
                    <input type="text" className="form-control" id="cc-number" name="ccNumber" required pattern="\d{13,19}" title="请输入13到19位银行卡号" 
                           value={paymentDetails.ccNumber} readOnly /> {/* 添加 readOnly */}
                    <div className="invalid-feedback">
                      请输入有效的银行卡号。
                    </div>
                  </div>

                  <div className="col-md-3">
                    <label htmlFor="cc-expiration" className="form-label">有效期</label>
                    <input type="text" className="form-control" id="cc-expiration" name="ccExpiration" placeholder="MM/YY" required pattern="(0[1-9]|1[0-2])\/?([0-9]{2})" title="格式: MM/YY" 
                           value={paymentDetails.ccExpiration} readOnly /> {/* 添加 readOnly */}
                    <div className="invalid-feedback">
                      请输入有效的有效期 (MM/YY)。
                    </div>
                  </div>

                  <div className="col-md-3">
                    <label htmlFor="cc-cvv" className="form-label">CVV</label>
                    <input type="text" className="form-control" id="cc-cvv" name="ccCvv" placeholder="" required pattern="\d{3,4}" title="请输入3或4位安全码"
                           value={paymentDetails.ccCvv} readOnly /> {/* 添加 readOnly */}
                    <div className="invalid-feedback">
                      请输入有效的CVV安全码。
                    </div>
                  </div>
                </div>

                <hr className="my-4" />

                <button className="w-100 btn btn-primary btn-lg" type="submit">
                  确认并支付 (使用预填信息)
                </button>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );

  return (
    <div className="container my-3 py-3">
      <h1 className="text-center">结算</h1>
      <hr />
      {cartItems.length ? <ShowCheckout /> : <EmptyCart />}
    </div>
  );
};

export default CheckoutPage;